package com.linkage.event.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.linkage.common.base.LocationVo;
import com.linkage.common.base.RequestInfo;
import com.linkage.common.base.ResponseInfo;
import com.linkage.common.constant.CommonSysConstant;
import com.linkage.common.util.RedisUtils;
import com.linkage.event.pojo.entity.UserLocation;
import com.linkage.event.pojo.vo.UserLocationVo;
import com.linkage.event.service.UserLocationService;
import com.linkage.event.utils.UserInterfUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 位置围栏信息controller
 */
@RestController
@RequestMapping("/electric")
@Slf4j
public class ElectronicFenceController {

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private UserLocationService userLocationService;


    /**
     * 获取位置信息
     * @param key
     * @return
     */
    @PostMapping("/redisValue")
    public String redisValue(@RequestParam String key){
        return ResponseInfo.success(JSONObject.parseObject(String.valueOf(redisUtils.get(key)),LocationVo.class)).toString();
    }

    /**
     * 添加位置
     * @param requestInfo
     * @return
     */
    @PostMapping("/addLocation")
    public String addLocation(@RequestBody RequestInfo<UserLocationVo> requestInfo){
        UserLocationVo vo = requestInfo.getBuss();
        if(StrUtil.hasEmpty(vo.getUserCode(),vo.getDptCode())){
            return ResponseInfo.error("用户或部门code为空").toString();
        }
        LocationVo locationVo = vo.getLocation();
        locationVo.setTimestamp(System.currentTimeMillis());
        Long timestamp = DateUtil.endOfDay(DateUtil.offset(new Date(), DateField.DAY_OF_YEAR,7)).getTime() - System.currentTimeMillis();
        redisUtils.set("location:"+vo.getDptCode()+":"+vo.getUserCode()+":"+ System.currentTimeMillis(), JSON.toJSONString(locationVo),timestamp/1000);
        return ResponseInfo.success().toString();
    }

    /**
     * 按时间区间查询
     * @param requestInfo
     *
     * @return
     */
    @PostMapping("/userLocationTrack")
    public String userLocationTrack(@RequestBody RequestInfo<Map> requestInfo){
        if(!requestInfo.getBuss().containsKey("userCode")){
            return ResponseInfo.error("userCode 参数为空").toString();
        }
        if(!requestInfo.getBuss().containsKey("timeInterval")){
            return ResponseInfo.error("timeInterval 参数为空").toString();
        }
        List<LocationVo> result = new ArrayList<>();
        //查询用户信息
        UserLocationVo user = UserInterfUtils.getUserInfo(requestInfo.getBuss().get("userCode").toString(),requestInfo.getBase().getUsertoken());
        Set<String> keySet = redisUtils.keys("location:"+user.getPersonOrgCode()+":"+user.getUserCode()+":*");
        List<String> keyList = new ArrayList<>();
        Long startTime = getStartEndTime(requestInfo.getBuss().get("timeInterval").toString());
        keySet.forEach(x -> {
            long time = Long.parseLong(x.split(":")[3]);
            if(time > startTime){
                keyList.add(x);
            }
        });
        result = redisUtils.multiGet(keyList,LocationVo.class);
        return ResponseInfo.success(result).toString();
    }

    /**
     * 获取时间区间开始时间
     * @param flag
     * @return
     */
    private Long getStartEndTime(String flag){
        Long startTime = null;
        switch (flag){
            //一天
            case "0":
                startTime = DateUtil.beginOfDay(DateUtil.offset(new Date(), DateField.DAY_OF_YEAR,-1)).getTime();
                break;
            //3天
            case "1":
                startTime = DateUtil.beginOfDay(DateUtil.offset(new Date(), DateField.DAY_OF_YEAR,-3)).getTime();
                break;
            //7天
            case "2":
                startTime = DateUtil.beginOfDay(DateUtil.offset(new Date(), DateField.DAY_OF_YEAR,-7)).getTime();
                break;
            default:
                startTime = DateUtil.beginOfDay(new Date()).getTime();
                break;
        }
        return startTime;
    }

    /**
     * 添加电子围栏
     * @param requestInfo
     * @return
     */
    @PostMapping("/addRanges")
    public String addRanges(@RequestBody RequestInfo<List<UserLocation>> requestInfo){
        List<UserLocation> list = requestInfo.getBuss();
        userLocationService.addUserLocations(list);
        return ResponseInfo.success("新增成功").toString();
    }

    /**
     * 根据创建人查询围栏信息
     * @param requestInfo
     * @return
     */
    @PostMapping("/queryRangeByCreate")
    public String queryByCreate(@RequestBody RequestInfo<Map<String, String>> requestInfo){
        Map<String, String> param = requestInfo.getBuss();
        if(!param.containsKey("create")){
            return ResponseInfo.error("创建人code参数不存在").toString();
        }
        List<UserLocation> list = userLocationService.queryLocationByCreate(param.get("create"));
        return ResponseInfo.success(list).toString();
    }


    /**
     * 删除围栏
     * @param requestInfo
     * @return
     */
    @PostMapping("/delRange")
    public String delRange(@RequestBody RequestInfo<Map<String, String>> requestInfo){
        Map<String, String> param = requestInfo.getBuss();
        if(!param.containsKey("code")){
            return ResponseInfo.error("code主键参数不存在").toString();
        }
        userLocationService.delUserLocation(UserLocation.builder()
                .code(param.get("code")).build());
        return ResponseInfo.success("删除成功").toString();
    }

}
